package model

import (
	"time"

	"gorm.io/gorm"
)

type (
	ResultModel interface {
		SearchResultByStuNo(StudentNo string) ([]Result, int64, error)
		//SearchResultByClassNo(ClassNo string) ([]Result, int64, error)
		AddResult(result *Result) (bool, error)
	}

	defaultResultModel struct {
		conn *gorm.DB
	}

	Result struct {
		gorm.Model
		StudentNo string `json:"studentNo"   gorm:"type:varchar(10)"`
		CreatedAt time.Time
		MBTI      string   `json:"mbti"     gorm:"type:varchar(5)"`
		Answer    string   `json:"answer"   gorm:"type:varchar(255)"`
		Student   *Student `json:"student"`
		StudentID uint
	}
)

func NewResultModel(conn *gorm.DB) ResultModel {
	//如果没有表则自动构建表
	conn.AutoMigrate(&Result{})
	return &defaultResultModel{
		conn: conn,
	}
}

//学号查询结果
func (d defaultResultModel) SearchResultByStuNo(StudentNo string) ([]Result, int64, error) {
	var result []Result
	var total int64
	err1 := d.conn.Model(&Result{}).Preload("Student").Where("student_no = ?", StudentNo).Find(&result).Error
	err2 := d.conn.Model(&Result{}).Preload("Student").Where("student_no = ?", StudentNo).Count(&total).Error
	if err1 != nil {
		return nil, 0, err1
	}
	if err2 != nil {
		return nil, 0, err2
	}
	return result, total, nil
}

//班级号查询结果
// func (d defaultResultModel) SearchResultByClassNo(ClassNo string) ([]Result, int64, error) {
// 	var result []Result
// 	var total int64
// 	err := d.conn.Model(&Result{}).Preload("Student").Where("class_no = ?", ClassNo).Find(&result).Error
// 	if err != nil {
// 		return nil, 0, err
// 	}
// 	return result, total, err
// }

//添加记录
func (d defaultResultModel) AddResult(result *Result) (bool, error) {
	err := d.conn.Model(result).Create(result).Error
	if err != nil {
		return false, err
	}
	return true, err
}
